package com.yj.proxy;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.yj.common.RpcRequest;
import com.yj.common.RpcResponse;
import com.yj.handler.RpcClientHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.*;

@Component
public class RpcProxy {



    //@Autowired
    //private RpcClientHandler rpcClientHandler;

    Executor executor = Executors.newFixedThreadPool(10);

    public Object createProxy(Class clazz) {
        return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                RpcClientHandler rpcClientHandler = new RpcClientHandler();
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(UUID.randomUUID().toString().replace("-",""));
                rpcRequest.setClassName(clazz.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                rpcClientHandler.setRequest(rpcRequest);
                //FutureTask futureTask = new FutureTask(rpcClientHandler);

                CompletableFuture<RpcResponse> future = rpcClientHandler.sendRequest(rpcRequest);
                RpcResponse rpcResponse = future.get();

                Object result = rpcResponse.getResult();
                return JSON.toJavaObject((JSON) result, method.getReturnType());
            }
        });
    }
}
